module("framework.core.eventsystem.EventItem",package.seeall)

---@class EventItem
local EventItem = class("EventItem")

local callWithCatch = _G.callWithCatch
local _xpcall = xpcall

--创建事件单位对象池
function EventItem.getPool()
    if nil == EventItem._pool then
        EventItem._pool = LuaObjPool.New(32, EventItem._poolNew, EventItem._poolRelease, EventItem._poolReset)
    end
    return EventItem._pool
end

function EventItem._poolNew()
    return EventItem.New()
end

function EventItem._poolRelease(luaObj)
    luaObj:release()
end

function EventItem._poolReset(luaObj)
    luaObj:reset()
end

function EventItem:ctor()
	self:reset()
end

function EventItem:release()
    self:reset()
end

function EventItem:ctor()
    self.cbObjContainer = {}
    setmetatable(self.cbObjContainer, {__mode = "v"})
    self:reset()
end

function EventItem:reset()
    self.eventName = nil
    self.callback = nil
    self.cbObjContainer.value = nil
    self.hasCbObj = false
    self.status = LuaEventSystem.Idle
    self.priority = LuaEventSystem.Low
    self.removeAll = nil
end

--使用弱引用保存事件回调对象
function EventItem:setCbObj(cbObj)
    self.hasCbObj = (nil ~= cbObj)
    if self.hasCbObj then
        self.cbObjContainer.value = cbObj
    end
end

--获取事件回调对象
function EventItem:getCbObj()
    if self.hasCbObj then
        return self.cbObjContainer.value 
    end
    return nil
end

--直接派发消息
function EventItem:dispatch(...)
    --如果事件回调是成员函数，并且回调对象被销毁了，则不回调
    if self.hasCbObj and not self.cbObjContainer.value then
        return false  
    end

    --1. IOS lua报错容易闪退 加try catch
    --2. 一个事件回调报错，会终止所有该事件所有回调，加上try catch处理
    if not self.hasCbObj then
        callWithCatch(self.callback, ...)
    else
        local args = ...
        local len = args ~= nil and select("#", ...) or 0
        if len > 0 then
            _xpcall(self.callback, __G__TRACKBACK__, self.cbObjContainer.value, select(1, ...))
        else
            _xpcall(self.callback, __G__TRACKBACK__, self.cbObjContainer.value)
        end
    end

    return true
end

return EventItem
